#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

#define N 64

int main(int argc, char const *argv[])
{
    // 接收广播
    int broadfd;
    // 创建一个socket文件描述符--广播的

    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (broadfd < 0)
    {
        perror("sock err");
        return -1;
    }

    // 绑定套接字(ip+port)
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8888);       // 端口号(小端转大端)
    addr.sin_addr.s_addr = INADDR_ANY; // 虚拟机IP地址

    int addrlen = sizeof(addr);
    // 绑定套接字
    if (bind(broadfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }

    // 接收客户端的信息参数
    ssize_t len;
    char buf[N] = {0};
    struct sockaddr_in cliaddr;

    // 接收"jianshenfang"搜索包
    while (1)
    {
        bzero(buf, N);
        len = recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&cliaddr, &addrlen);
        if (len < 0)
        {
            printf("recvbroad err\n");
            return -1;
        }
        // 判断是否是本公司产品：收到的数据是否"jianshenfang"
        if (strcmp(buf, "jianshenfang") == 0)
        {
            printf("is my jianshenfang\n");
            break;
        }
        else
        {
            printf("not my jianshenfang\n");
        }
    }

    // 回复yes，告诉软件，我收到了搜索协议，并且回复地址
    sendto(broadfd, "yes", sizeof("yes"), 0, (struct sockaddr *)&cliaddr, addrlen);
    printf("回复成功,准备连接\n");

    // 变身为TCP服务器，准备接收软件的升级文件
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcpfd < 0)
    {
        perror("tcpsock err");
        return -1;
    }
    // 直接复用addr,因为都在虚拟机内，所以本机IP都是一样的，不改变端口号可以直接复用
    if (bind(tcpfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("tcpbind err");
        return -1;
    }

    // 监听套接字
    if (listen(tcpfd, 5) < 0)
    {
        perror("tcplisten err");
        return -1;
    }

    // 接收客户端的连接
    printf("wait client connect\n");

    int ret;
    char msg[4 * N];
    while (1)
    {
        // 接收对端的地址
        int clifd = accept(tcpfd, NULL, NULL);
        if (clifd < 0)
        {
            perror("accept err");
            return -1;
        }
        printf("new cononect coming\n");
        // 接收发送消息（send recv）
        while (1)
        {
            ret = recv(clifd, msg, sizeof(msg), 0);
            if (ret < 0)
            {
                perror("recv err");
                return -1;
            }
            else if (ret == 0)
            {
                printf("client exit\n");
                break;
            }
            // read(clifd,msg,sizeof(msg));
            printf("msg:%s\n", msg);
            memset(msg, 0, sizeof(msg));
        }
        // 7.关闭套接字（close）
        close(clifd);
    }
    close(broadfd);
    close(tcpfd);
    return 0;
}
